package com.leetcode.contest;

import java.util.*;

/**
 * @author `RKC`
 * @date 2021/11/13 9:47
 */
public class LC2034股票价格波动 {

    private static class StockPrice {
        private PriorityQueue<int[]> maxQueue = new PriorityQueue<>((o1, o2) -> Integer.compare(o2[1], o1[1]));
        private PriorityQueue<int[]> minQueue = new PriorityQueue<>((o1, o2) -> Integer.compare(o1[1], o2[1]));
        private TreeMap<Integer, Integer> treeMap = new TreeMap<>();

        public StockPrice() {

        }

        public void update(int timestamp, int price) {
            treeMap.put(timestamp, price);
            int[] ele = {timestamp, price};
            maxQueue.offer(ele);
            minQueue.offer(ele);
        }

        public int current() {
            return treeMap.lastEntry().getValue();
        }

        public int maximum() {
            //要求大顶堆中的最大元素在treeMap中
            while (!maxQueue.isEmpty() && (treeMap.get(maxQueue.peek()[0]) != maxQueue.peek()[1])) {
                maxQueue.poll();
            }
            return maxQueue.peek()[1];
        }

        public int minimum() {
            //要求小顶堆中的最小元素在treeMap中
            while (!minQueue.isEmpty() && (treeMap.get(minQueue.peek()[0]) != minQueue.peek()[1])) {
                minQueue.poll();
            }
            return minQueue.peek()[1];
        }
    }

    public static void main(String[] args) {
        StockPrice stockPrice = new StockPrice();
        stockPrice.update(1, 10);
        stockPrice.update(2, 5);
        System.out.println(stockPrice.current());
        System.out.println(stockPrice.maximum());
        stockPrice.update(1, 3);
        System.out.println(stockPrice.maximum());
        stockPrice.update(4, 2);
        System.out.println(stockPrice.minimum());
    }
}
